package minio

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"go-admin/global"
	"go-admin/pkg/setting"
)

var (
	MinioClient *minio.Client
)

// 实例化minio
func newMinio(minioSetting *setting.MinioSetting) (*minio.Client, error) {
	ctx := context.Background()
	address := fmt.Sprintf("%v:%d", minioSetting.Host, minioSetting.Port)
	client, err := minio.New(address, &minio.Options{
		Creds:  credentials.NewStaticV4(minioSetting.AccessKeyID, minioSetting.SecretAccessKey, ""),
		Secure: minioSetting.UseSSL,
	})
	if err != nil {
		return nil, err
	}
	// 新建桶
	if err = client.MakeBucket(ctx, minioSetting.BucketName, minio.MakeBucketOptions{Region: minioSetting.Location}); err != nil {
		// 检查桶是否存在
		exists, err := client.BucketExists(ctx, minioSetting.BucketName)
		if err == nil && exists {
			fmt.Println("当前桶已经存在")
		} else {
			fmt.Println(err)
			return nil, err
		}
	}
	return client, nil
}

// 加载minio
func SetupMinio() error {
	var err error
	MinioClient, err = newMinio(global.MinioSetting)
	if err != nil {
		return err
	}
	return nil
}
